/*
 * @Author: your name
 * @Date: 2021-08-30 20:44:34
 * @LastEditTime: 2022-01-04 07:30:16
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \phone\src\input_password.cpp
 */
#include "input_password.h"
InputPassword::InputPassword(std::unique_ptr<Widget> &page, std::string &value, Widget *editView, bool commonInputItem)
    : InputItem(page, value, editView, commonInputItem), primaryWidget(page)
{
    run = false;
}
InputPassword::~InputPassword()
{
    if (run)
    {
        showTime = STOP_SHOW_TIME;
    }
    while (run)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(100));
    }
    std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
void InputPassword::SetEditString(Widget *widget, std::string value, unsigned int index)
{
    char text[256] = {0};
    snprintf(text, 256, "default(w=%d,h=100%%)", CURSOR_WIDTH);
    GuiEngine::GetInstance().SetSelfLayout(widget, text);
    GuiEngine::GetInstance().SetTextUtf8(widget, GetValueByIndex(value, index).c_str());
    GuiEngine::GetInstance().UseStyle(widget, "inputEdit");
    if (GetCursor() == index + 1)
    {
        GuiEngine::GetInstance().SetName(widget, "textItself");
        std::thread t(&InputPassword::TextItselfHandle, this);
        t.detach(); //设置线程分离属性，线程结束后自动释放资源
    }
}
void InputPassword::TextItselfHandle()
{
    auto funCallback = [](void *ctx)
    {
        IS_VALID_PTR(ctx)
        Context *p = (Context *)ctx;
        delete p;
        InputPassword *im = dynamic_cast<InputPassword *>(InputMethod::GetInstance());
        IS_VALID_PTR(im)
        im->TextItselfHandleIQ();
    };
    const unsigned int SLEEP_TIME = 100;
    showTime = 0;
    m_mutex.lock();
    if (run)
    {
        m_mutex.unlock();
        return;
    }
    run = true;
    m_mutex.unlock();
    while (run)
    {
        std::this_thread::sleep_for(std::chrono::milliseconds(SLEEP_TIME));
        showTime += SLEEP_TIME;
        if (showTime >= STOP_SHOW_TIME)
        {
            m_mutex.lock();
            break;
        }
    }
    CommonFunc::GetInstance().GuiIdleQueue(funCallback);
    run = false;
    m_mutex.unlock();
}
void InputPassword::TextItselfHandleIQ()
{
    std::unique_ptr<Widget> view(GuiEngine::GetInstance().NewWidget());
    if (GuiEngine::GetInstance().Lookup(primaryWidget.get(), "textItself", true, view.get()))
    {
        GuiEngine::GetInstance().SetTextUtf8(view.get(), "*");
    }
    // m_mutex.lock();
    // run = false;
    // m_mutex.unlock();
}
std::string InputPassword::GetString()
{
    std::string str;
    str.assign(InputItem::GetString().length(), '*');
    return str;
}
std::string InputPassword::GetValueByIndex(std::string value, unsigned int index)
{
    if (index + 1 == GetCursor())
    {
        return InputItem::GetValueByIndex(value, index);
    }
    return "*";
}